package com.inventive.jmscache.server;

import com.inventive.jmscache.server.utils.CollectionEnumeration;
import com.inventive.jmscache.server.utils.IteratorEnumeration;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import java.util.Enumeration;

/**
 * Created by IntelliJ IDEA.
 */
public class JmsCacheQueueBrowser implements QueueBrowser {

    private JmsCacheQueue queue;
    private String messageSelector;
    private boolean closed = false;

    public JmsCacheQueueBrowser(JmsCacheQueue queue, String messageSelector) {
        this.queue = queue;
        this.messageSelector = messageSelector;
    }

    public Queue getQueue() throws JMSException {
        checkClosed();
        return queue;
    }

    public String getMessageSelector() throws JMSException {
        checkClosed();
        return messageSelector;
    }

    public Enumeration getEnumeration() throws JMSException {
        checkClosed();
        return new IteratorEnumeration<JmsCacheMessage>(queue.getMessageIterator(messageSelector));
    }

    protected void checkClosed() throws JMSException {
        if (closed) {
            throw new JMSException("JMSCacheQueueBrowser is already closed");
        }
    }

    public void close() throws JMSException {
        checkClosed();
        closed = true;
    }
}
